package com.zsc.boot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zsc.boot.bean.Team;

import com.zsc.boot.bean.User;
import com.zsc.boot.bean.UserTeam;
import com.zsc.boot.bean.dto.TeamQuery;
import com.zsc.boot.common.ErrorType;
import com.zsc.boot.common.PageRequest;
import com.zsc.boot.common.TeamStatusEnums;
import com.zsc.boot.exception.BusinessException;
import com.zsc.boot.mapper.TeamMapper;
import com.zsc.boot.service.TeamService;
import com.zsc.boot.service.UserTeamService;
import io.swagger.models.auth.In;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 *
 */
@Service
@Transactional(rollbackFor = Exception.class)//开启事务,事务回滚抛异常
public class TeamServiceImpl extends ServiceImpl<TeamMapper, Team>
    implements TeamService {

    @Resource
    private UserTeamService userTeamService;

    @Override
    public long createTeam(Team team, User loginUser) {
        //1. 请求参数是否为空？
        if(team == null){
            throw new BusinessException(ErrorType.PARAMS_ERROR);
        }
        //2. 是否登录，未登录不允许创建
        if(loginUser == null){
            throw new BusinessException(ErrorType.NOT_LOGIN);
        }
        long userId = loginUser.getId();
        //3. 校验信息
        //   1. 队伍人数 > 1 且 <= 20
        int teamNum = Optional.ofNullable(team.getMaxNum()).orElse(0);
        if(teamNum < 1 || teamNum > 20){
            throw new BusinessException(ErrorType.PARAMS_ERROR,"队伍人数错误");
        }
        //   2. 队伍标题 <= 20
        String teamName = team.getName();
        if(StringUtils.isBlank(teamName) || teamName.length() > 20){
            throw new BusinessException(ErrorType.PARAMS_ERROR,"队伍标题错误");
        }
        //   3. 描述 <= 512
        String description = team.getDescription();
        if(StringUtils.isNotBlank(description) && description.length() > 512){
            throw new BusinessException(ErrorType.PARAMS_ERROR,"队伍描述错误");
        }
        //获取当前队伍的状态
        int status =Optional.ofNullable(team.getStatus()).orElse(0);
        TeamStatusEnums teamStatusEnums = TeamStatusEnums.getEnumByNum(status);
        //   4. status 是否公开（int）不传默认为 0（公开）
        if(teamStatusEnums == null){
            throw new BusinessException(ErrorType.PARAMS_ERROR,"队伍状态错误");
        }
        //   5. 如果 status 是加密状态，一定要有密码，且密码 <= 32
        String password = team.getPassword();
        if(TeamStatusEnums.SECRET.equals(teamStatusEnums)){//如果 status 是加密状态
            if(StringUtils.isBlank(password) || password.length() > 32){
                throw new BusinessException(ErrorType.PARAMS_ERROR,"密码设置错误");
            }
        }
        //   6. 超时时间 > 当前时间
        Date expireTime = team.getExpireTime();
        if(new Date().after(expireTime)){//当前时间在过期时间之后，那就异常
            throw new BusinessException(ErrorType.PARAMS_ERROR,"超时时间异常");
        }

        //   7. 校验用户最多创建 5 个队伍
        // todo 有bug，用户可以创建100个队伍【需要使用锁】
        QueryWrapper<Team> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId",userId);//判断当前队伍是由当前用户创建的
        long count = this.count(queryWrapper);
        if(count >= 5){
            throw new BusinessException(ErrorType.PARAMS_ERROR,"用户最多创建5个队伍");
        }
        //4. 插入队伍信息到队伍表
        team.setId(null);
        team.setUserId(userId);
        boolean save = this.save(team);
        if(!save){
            throw new BusinessException(ErrorType.PARAMS_ERROR,"队伍插入不成功");
        }
        //5. 插入用户  => 队伍关系到关系表
        UserTeam userTeam = new UserTeam();
        userTeam.setUserId(userId);
        userTeam.setTeamId(team.getId());
        userTeam.setJoinTime(new Date());

        boolean result = userTeamService.save(userTeam);
        if(!result){
            throw new BusinessException(ErrorType.PARAMS_ERROR,"用户队伍关系表插入不成功");
        }
        return team.getId(); //这个team的id是新插入后team的id
    }

    /**
     * 查询队伍
     * @param teamQuery
     * @return
     */
    @Override
    public List<Team> listTeam(TeamQuery teamQuery) {
        QueryWrapper<Team> queryWrapper = new QueryWrapper<>();
        //1、组合查询条件
        if(teamQuery != null){
            Long id = teamQuery.getId();
            if(id != null){
                queryWrapper.eq("id",id);
            }

            String name = teamQuery.getName();
            if(StringUtils.isNotBlank(name)){
                queryWrapper.like("name",name);
            }

            String description = teamQuery.getDescription();
            if(StringUtils.isNotBlank(description)){
                queryWrapper.like("description",description);
            }

            //查询最大人数相等的
            Integer maxNum = teamQuery.getMaxNum();
            if(maxNum != null && maxNum > 0){
                queryWrapper.eq("maxNum",maxNum);
            }

            //根据创建人查询
            Long userId = teamQuery.getUserId();
            if(userId != null && userId > 0){
                queryWrapper.eq("userId",userId);
            }

            Integer status = teamQuery.getStatus();
            if(status != null){
                queryWrapper.eq("status",status);
            }
        }
        return null;
    }
}




